package bma.common.netty.jvm;

import java.util.List;

import org.jboss.netty.channel.group.ChannelGroup;

import bma.common.langutil.core.ObjectPair;
import bma.common.langutil.core.StringUtil;
import bma.common.langutil.jmshell.JMShellUtil;
import bma.common.langutil.jmshell.Session;
import bma.common.langutil.jmshell.cmdopt.CommandOptionParser;
import bma.common.langutil.jmshell.command.AbstractSimpleCommandProcessor;
import bma.common.netty.NettySquare;
import bma.common.netty.jvm.NettyListCommand.NettyInfo;

public class NettyBindCommand extends AbstractSimpleCommandProcessor {

	public NettyBindCommand() {
		super("bind");
		setArgsTips("[name]");
	}

	@Override
	public CommandOptionParser createCommandOption(Session session) {
		CommandOptionParser r = new CommandOptionParser();
		return r;
	}

	@Override
	public boolean processCommand(Session session, String cmd,
			CommandOptionParser options) {
		String[] args = options.getRemainingArgs();
		if (args != null && args.length > 0) {
			bind(session, args[0]);
			return true;
		}
		show(session);
		return true;
	}

	public void show(Session s) {
		NettyInfo info = JMShellUtil.getData(s, NettyListCommand.DATA_KEY,
				NettyListCommand.NettyInfo.class, true);
		s.writeln("[netty]");
		if (info != null) {
			s.writeln("name:  " + info.groupName);
			s.writeln("group: " + info.group);
		}
		List<ObjectPair<String, ChannelGroup>> glist = NettySquare.listGroup();

		s.writeln("[netty channel group list]");
		for (ObjectPair<String, ChannelGroup> op : glist) {
			String n = op.getValue();
			ChannelGroup g = op.getAttribute();
			s.writeln(n + ": " + g.size());
		}
		s.writeln("[netty done]");
	}

	public void bind(Session s, String name) {

		List<ObjectPair<String, ChannelGroup>> glist = NettySquare.listGroup();
		ChannelGroup g = null;
		for (ObjectPair<String, ChannelGroup> op : glist) {
			if (StringUtil.equals(op.getValue(), name)) {
				g = op.getAttribute();
				break;
			}
		}
		if (g == null) {
			s.writeln("ERROR: '" + name + "' not found");
			return;
		}

		NettyInfo info = JMShellUtil.getData(s, NettyListCommand.DATA_KEY,
				NettyListCommand.NettyInfo.class, true);
		info.groupName = name;
		info.group = g;

		NettyListCommand.resetPager(s);

		s.writeln("bind done");
	}
}